<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="《Python Django Web典型模块开发实战》（上）, blog">
    <meta name="description" content="这是我的个人网站，欢迎来访">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>《Python Django Web典型模块开发实战》（上） | 头号咸鱼</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

    <script>(function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/7b318e23.js","daovoice")</script>
    

<meta name="generator" content="Hexo 5.3.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="头号咸鱼" type="application/atom+xml">
</head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">头号咸鱼</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">头号咸鱼</div>
        <div class="logo-desc">
            
            这是我的个人网站，欢迎来访
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-g8zz57.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">《Python Django Web典型模块开发实战》（上）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%94%B5%E5%AD%90%E4%B9%A6/">
                                <span class="chip bg-color">电子书</span>
                            </a>
                        
                            <a href="/tags/Django/">
                                <span class="chip bg-color">Django</span>
                            </a>
                        
                            <a href="/tags/%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB/">
                                <span class="chip bg-color">前后端分离</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%90%8E%E7%AB%AF%E6%A1%86%E6%9E%B6/" class="post-category">
                                后端框架
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-02-24
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2021-02-24
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    14.6k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    78 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>这本书对我的帮助很大，我通过这本书实现了<strong>前后端分析项目</strong>，<strong>邮件注册登录</strong>，<strong>网站部署</strong>等自己在网上学不到的东西，很有用的进阶Django教程，这本书是自己在图书馆租的，有时候喜欢到一楼的新书书架看看计算机类的新书，目前就这本书学到手了哈。博客整理的是重要步骤和代码，书上的理论也不多，有的读者评论个缺点。我感觉还好，就是喜欢这种类型的，自己的整理还可以，特别是最后一章的项目部署。</p>
</blockquote>
<h2 id="第二章：实现豆瓣api应用"><a href="#第二章：实现豆瓣api应用" class="headerlink" title="第二章：实现豆瓣api应用"></a>第二章：实现豆瓣api应用</h2><h4 id="1-Django-REST-framework序列化"><a href="#1-Django-REST-framework序列化" class="headerlink" title="1.Django REST framework序列化"></a>1.Django REST framework序列化</h4><h6 id="用serializers-Serializer方式序列化"><a href="#用serializers-Serializer方式序列化" class="headerlink" title="用serializers.Serializer方式序列化"></a>用serializers.Serializer方式序列化</h6><ol>
<li>创建项目book</li>
<li>安装rf及其依赖包</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>在settings中注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'rest_framework'
]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>设计user的model.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
    """
    用户
    """
    APIkey=models.CharField(max_length=30,verbose_name='APIkey',default='abcdefghigklmn')
    money=models.IntegerField(default=10,verbose_name='余额')
    class Meta:
        verbose_name='用户'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.username
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>在setting中配置用户表的继承代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">AUTH_USER_MODEL='users.UserProfile'<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="6">
<li>在model.py创建信息表book</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from datetime import datetime
from django.db import models
class Book(models.Model):
    """
    书籍信息
    """
    title=models.CharField(max_length=30,verbose_name='书名',default='')
    isbn=models.CharField(max_length=30,verbose_name='isbn',default='')
    author=models.CharField(max_length=20,verbose_name='作者',default='')
    publish=models.CharField(max_length=30,verbose_name='出版社',default='')
    rate=models.FloatField(default=0,verbose_name='豆瓣评分')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='书籍信息'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>更新数据，创建超级用户</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser
Username: admin
邮箱: 1@1.com
Password:
Password (again):<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>在user目录下创建serializers.py文件</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers
from .models import UserProfile,Book
class BookSerializer(serializers.Serializer):
    title=serializers.CharField(required=True,max_length=100)
    isbn=serializers.CharField(required=True,max_length=100)
    author=serializers.CharField(required=True,max_length=100)
    publish=serializers.CharField(required=True,max_length=100)
    rate=serializers.FloatField(default=0)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>在user/views中编写</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from .serializers import BookSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile,Book
class BookAPIView1(APIView):
    """
    使用Serializer
    """
    def get(self, request, format=None):
        APIKey=self.request.query_params.get("apikey", 0)
        developer=UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            balance=developer.money
            if balance&gt;0:
                isbn = self.request.query_params.get("isbn", 0)
                books = Book.objects.filter(isbn=int(isbn))
                books_serializer = BookSerializer(books, many=True)
                developer.money-=1
                developer.save()
                return Response(books_serializer.data)
            else:
                return Response("兄弟，又到了需要充钱的时候！好开心啊！")
        else:
            return Response("查无此人啊")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="10">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1
urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook1/',BookAPIView1.as_view(),name='book1'),
]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>测试省略</p>
</blockquote>
<h6 id="用serializers-ModelSerializer方式序列化-接上"><a href="#用serializers-ModelSerializer方式序列化-接上" class="headerlink" title="用serializers.ModelSerializer方式序列化(接上)"></a>用serializers.ModelSerializer方式序列化(接上)</h6><p>1.编写user/serlializer.py</p>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers
from .models import UserProfile,Book
class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields="__all__"#将整个表的所有字段都序列化
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>编写views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from .serializers import BookModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile,Book
class BookAPIView2(APIView):
    """
    使用ModelSerializer
    """
    def get(self, request, format=None):
        APIKey=self.request.query_params.get("apikey", 0)
        developer=UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            balance=developer.money
            if balance&gt;0:
                isbn = self.request.query_params.get("isbn", 0)
                books = Book.objects.filter(isbn=int(isbn))
                books_serializer = BookModelSerializer(books, many=True)
                developer.money-=1
                developer.save()
                return Response(books_serializer.data)
            else:
                return Response("兄弟，又到了需要充钱的时候！好开心啊！")
        else:
            return Response("查无此人啊")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>3.配置路由</p>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1,BookAPIView2
urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook1/',BookAPIView1.as_view(),name='book1'),
    path('apibook2/',BookAPIView2.as_view(),name='book2'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>测试省略</p>
</blockquote>
<blockquote>
<p>对特定字段序列化</p>
<pre class="line-numbers language-none"><code class="language-none">class BookModelSerializer(serializers.ModelSerializer):
 class Meta:
     model = Book
     # fields="__all__"#将整个表的所有字段都序列化
     fields = ('title', 'isbn', 'author')  # 指定序列化某
     些字段<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</blockquote>
<h4 id="2-Django-REST-framework试图三层封装"><a href="#2-Django-REST-framework试图三层封装" class="headerlink" title="2.Django REST framework试图三层封装"></a>2.Django REST framework试图三层封装</h4><h6 id="用mixins-ListModelMixin-generics-GenericAPIView的方式实现试图封装"><a href="#用mixins-ListModelMixin-generics-GenericAPIView的方式实现试图封装" class="headerlink" title="用mixins.ListModelMixin+generics.GenericAPIView的方式实现试图封装"></a>用mixins.ListModelMixin+generics.GenericAPIView的方式实现试图封装</h6><pre class="line-numbers language-none"><code class="language-none">from .serializers import BookModelSerializer
from rest_framework.response import Response
from .models import UserProfile,Book
from rest_framework import mixins
from rest_framework import generics
ookMixinView1(mixins.ListModelMixin,generics.GenericAPIView):
    queryset=Book.objects.all()
    serializer_class = BookModelSerializer
    def get(self,request,*args,**kwargs):#如果这里不加get函数，代表默认不支持get访问这个api，所以必须加上
        APIKey = self.request.query_params.get("apikey", 0)
        developer = UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            balance=developer.money
            if balance&gt;0:
                isbn = self.request.query_params.get("isbn", 0)
                developer.money -= 1
                developer.save()
                self.queryset = Book.objects.filter(isbn=int(isbn))
                return self.list(request, *args, **kwargs)
            else:
                return Response("兄弟，又到了需要充钱的时候！好开心啊！")
        else:
            return Response("查无此人啊")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>配置路由</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1,BookAPIView2
from users.views import BookMixinView1
urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook1/',BookAPIView1.as_view(),name='book1'),
    path('apibook2/',BookAPIView2.as_view(),name='book2'),
    path('apibook3/',BookMixinView1.as_view(),name='book3'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="用generics-ListAPIView的方式实现试图封装"><a href="#用generics-ListAPIView的方式实现试图封装" class="headerlink" title="用generics.ListAPIView的方式实现试图封装"></a>用generics.ListAPIView的方式实现试图封装</h6><pre class="line-numbers language-none"><code class="language-none">from .serializers import BookModelSerializer
from rest_framework.response import Response
from .models import UserProfile,Book
from rest_framework import mixins
from rest_framework import generics
class BookMixinView2(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookModelSerializer
    def get(self,request,*args,**kwargs):
        APIKey = self.request.query_params.get("apikey", 0)
        developer = UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            balance=developer.money
            if balance&gt;0:
                isbn = self.request.query_params.get("isbn", 0)
                developer.money -= 1
                developer.save()
                self.queryset = Book.objects.filter(isbn=int(isbn))
                return self.list(request, *args, **kwargs)
            else:
                return Response("兄弟，又到了需要充钱的时候！好开心啊！")
        else:
            return Response("查无此人啊")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>配置路由</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1,BookAPIView2
from users.views import BookMixinView1,BookMixinView2
urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook1/',BookAPIView1.as_view(),name='book1'),
    path('apibook2/',BookAPIView2.as_view(),name='book2'),
    path('apibook3/',BookMixinView1.as_view(),name='book3'),
    path('apibook4/',BookMixinView2.as_view(),name='book4'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h6 id="用viewset-Router的方式实现视图封装"><a href="#用viewset-Router的方式实现视图封装" class="headerlink" title="用viewset+Router的方式实现视图封装"></a>用viewset+Router的方式实现视图封装</h6><pre class="line-numbers language-none"><code class="language-none">from .serializers import BookModelSerializer
from rest_framework.response import Response
from .models import UserProfile,Book
from rest_framework import viewsets
from rest_framework.permissions import BasePermission
class IsDeveloper(BasePermission):
    message='查无此人啊'
    def has_permission(self,request,view):
        APIKey = request.query_params.get("apikey", 0)
        developer = UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            return True
        else:
            print(self.message)
            return False
class EnoughMoney(BasePermission):
    message = "兄弟，又到了需要充钱的时候！好开心啊！"
    def has_permission(self,request,view):
        APIKey = request.query_params.get("apikey", 0)
        developer = UserProfile.objects.filter(APIkey=APIKey).first()
        balance = developer.money
        if balance &gt; 0:
            developer.money -= 1
            developer.save()
            return True
        else:
            return False
class BookModelViewSet(viewsets.ModelViewSet):
    authentication_classes = []
    permission_classes = [IsDeveloper, EnoughMoney]
    queryset = Book.objects.all()
    serializer_class = BookModelSerializer
    def get_queryset(self):
        isbn = self.request.query_params.get("isbn", 0)
        books = Book.objects.filter(isbn=int(isbn))
        queryset=books
        return queryset
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>配置路由</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from users.views import BookAPIView2
from users.views import BookMixinView1,BookMixinView2
from users.views import BookModelViewSet
from rest_framework.routers import DefaultRouter
from django.conf.urls import include
router=DefaultRouter()
router.register(r'apibook5',BookModelViewSet)
urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook2/',BookAPIView2.as_view(),name='book2'),
    path('apibook3/',BookMixinView1.as_view(),name='book3'),
    path('apibook4/',BookMixinView2.as_view(),name='book4'),
    path('',include(router.urls))
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<h2 id="第三章：用Django设计大象电商的类别表"><a href="#第三章：用Django设计大象电商的类别表" class="headerlink" title="第三章：用Django设计大象电商的类别表"></a>第三章：用Django设计大象电商的类别表</h2><h4 id="1-用vue-js在前端开发一个电商导航栏项目demo1"><a href="#1-用vue-js在前端开发一个电商导航栏项目demo1" class="headerlink" title="1. 用vue.js在前端开发一个电商导航栏项目demo1"></a>1. 用vue.js在前端开发一个电商导航栏项目demo1</h4><ol>
<li>下载并且安装node.js</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">node -v #查看版本，检验是否安装成功<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>安装淘宝镜像cnpm</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">npm install -g cnpm --registry=https://registry.npm.taobao.org<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>安装vue.js脚手架</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">cnpm install --global vue-cli<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="4">
<li>创建项目</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">vue init webpack-simple demo1<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>进入目录，安装依赖，运行</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">cd demo1

cnpm install

npm run dev<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>修改App.vue</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;div class="all"&gt;
      &lt;div class="one"&gt;
        &lt;div class="onetype" v-for="(item,index) in one" :key="index"&gt;
          &lt;b&gt;{{one[index]}}&lt;/b&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="twothreefour"&gt;
        &lt;div class="two"&gt;
          &lt;div class="twotype" 
          v-for="(item,index) in two" :key="index"
           @mouseenter="open(index)"&gt;
            &lt;b&gt;{{two[index]}}&lt;/b&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="threefour" v-if="flag"
           @mouseleave="close()"&gt;
          &lt;div class="threefourtype" v-for="(item,index) in three" :key="index"&gt;
            &lt;span class="three"&gt;{{three[index]}}&lt;/span&gt;
           &lt;span class="four" v-for="(item4,index4) in four" :key="index4"&gt;{{four[index4]}}&lt;/span&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

&lt;/template&gt;


&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      one:['一级类目','一级类目','一级类目','一级类目','一级类目'],
      two:['二级类目1','二级类目2','二级类目3','二级类目4','二级类目5'],
      three:[],
      four:['四级类目','四级类目','四级类目','四级类目','四级类目'],
      flag:false
    }
  },
  methods: {
    open(index){
      var index=index+1;
      var i=index+"";
      this.three=['三级目录'+i,'三级目录'+i,'三级目录'+i,'三级目录'+i,'三级目录'+i]
      this.flag=true
    },
    close(){
      this.flag=false
    }
  },
}
&lt;/script&gt;



&lt;style&gt;
*{
  /* 样式初始化 */
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
.all{
  /* 将整个导航栏组件做整体设置 */
  /*宽度占浏览器80%，高度400px；背景灰色；上外边距50px; 左右居中*/
  /* 设置为flex弹性盒子，并且定义为高度不够自动折行模式，用于横向排列子元素 */
  width: 80%;
  height: 400px;
  background:#eee;
  margin: 50px auto;
  display: -webkit-flex; /* Safari */
  display: flex;
  flex-wrap: wrap;
}
.one{
  /* 设置一级类目所占地区的样式，宽度占满all盒子的100% */
  width: 100%;
  height: 50px;
  background: #FF8888;
  display: flex;
  display: -webkit-flex; /* Safari */
  flex-wrap: wrap;
  /* 弹性盒子内部的子元素都均匀排列成一横排，并且左右两边都留有一定空隙 */
  justify-content: space-around;
}
.onetype{
  width: 20%;
  height: 50px;
  line-height: 50px;
  text-align: center;
}
.onetype:hover{ 
  background-color:chocolate;
  color: #eee;
}
.twothreefour{
  /* 盛放二三四级目录的盒子 */
  width: 100%;
  height: 350px;
  background: #66FF66;
  display: -webkit-flex; /* Safari */
  display: flex;
  flex-wrap: wrap;
  /* 弹性盒子内部的子元素都均匀排列成一横排，并且左右两边都不留空隙 */
  justify-content: space-between;
}
.two{
  /* 设置盛放二级类目的弹性盒子 */
  width: 15%;
  height: 100%;
  background: #77FFCC;
  display: -webkit-flex; /* Safari */
  display: flex;
  /* 弹性盒子内部的子元素从上到下排成一列 */
  flex-direction: column;
}
.twotype{
  width: 100%;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #EEFFBB;
}
.twotype:hover{ 
  background-color:black;
  color: #eee;
}
.threefour{
  width: 40%;
  margin-right: 45%;
  height: 100%;
  background: #33FFDD;
  display: -webkit-flex; /* Safari */
  display: flex;
  flex-direction: column;
}
.threefourtype{
  margin: 10px auto;
}
.three{
  font-family: 微软雅黑, 黑体;
  font-size: 16px;
  font-weight: 800;
}
.four{
  font-family: 宋体;
  font-size: 12px;
  font-weight: 400;
}
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-建立pycharm创建项目"><a href="#2-建立pycharm创建项目" class="headerlink" title="2.建立pycharm创建项目"></a>2.建立pycharm创建项目</h4><ol>
<li>创建demo2，新建APP命名app01</li>
<li>安装相关依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install Djangorestframework markdown Django-filter pillow Django-guardian coreapi<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>setting中注册rest_framework</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'Django.contrib.admin',
    'Django.contrib.auth',
    'Django.contrib.contenttypes',
    'Django.contrib.sessions',
    'Django.contrib.messages',
    'Django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>model.py新建类别表</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from Django.db import models
from datetime import datetime
# Create your models here.
class Type1(models.Model):
    """
    一级类目
    """
    name=models.CharField(max_length=10,default="",verbose_name="类目名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name = '商品类别'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
class Type2(models.Model):
    """
    二级类目
    """
parent=models.ForeignKey(Type1,verbose_name="父级类别",
null=True,blank=True,on_delete=models.CASCADE)
    name=models.CharField(max_length=10,default="",verbose_name="类目名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name = '商品类别2'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
class Type3(models.Model):
    """
    三级类目
    """
parent=models.ForeignKey(Type2,verbose_name="父级类别",
null=True,blank=True,on_delete=models.CASCADE)
    name=models.CharField(max_length=10,default="",verbose_name="类目名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name = '商品类别3'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
class Type4(models.Model):
    """
    四级类目
    """
parent=models.ForeignKey(Type3,verbose_name="父级类别",
null=True,blank=True,on_delete=models.CASCADE)
    name=models.CharField(max_length=10,default="",verbose_name="类目名")
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name = '商品类别4'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>数据更新命令</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="6">
<li>完善demo2的后台逻辑代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers #引入序列化模块
from .models import Type1,Type2,Type3,Type4 #引入所有数据表类
class Type1ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Type1
        fields="__all__"
class Type2ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Type2
        fields="__all__"
class Type3ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Type3
        fields="__all__"
class Type4ModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Type4
        fields="__all__"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">#引入序列化类
from .serializers import Type1ModelSerializer,Type2ModelSerializer
from .serializers import Type3ModelSerializer,Type4ModelSerializer
#引入数据表
from .models import Type1,Type2,Type3,Type4
#引入rest_framework相关模块
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
# Create your views here.
class Type1View(APIView):
    """
    all Type1
    """
    renderer_classes = [JSONRenderer]
    def get(self, request, format=None):
        types=Type1.objects.all()
        types_serializer = Type1ModelSerializer(types, many=True)
        return Response(types_serializer.data)
class Type2View(APIView):
    """
    all Type2
    """
    renderer_classes = [JSONRenderer]
    def get(self, request, format=None):
        types=Type2.objects.all()
        types_serializer = Type2ModelSerializer(types, many=True)
        return Response(types_serializer.data)
class Type3View(APIView):
    """
    all Type3
    """
    renderer_classes = [JSONRenderer]
    def get(self, request, format=None):
        types=Type3.objects.all()
        types_serializer = Type3ModelSerializer(types, many=True)
        return Response(types_serializer.data)
class Type4View(APIView):
    """
    all Type4
    """
    renderer_classes = [JSONRenderer]
    def get(self, request, format=None):
        types=Type4.objects.all()
        types_serializer = Type4ModelSerializer(types, many=True)
        return Response(types_serializer.data)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>添加路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from Django.contrib import admin
from Django.urls import path
#引入视图类
from app01.views import Type1View,Type2View,Type3View,Type4View
urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/type1/',Type1View.as_view()),
    path('api/type2/',Type2View.as_view()),
    path('api/type3/',Type3View.as_view()),
    path('api/type4/',Type4View.as_view())
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-前后端项目联合"><a href="#3-前后端项目联合" class="headerlink" title="3.前后端项目联合"></a>3.前后端项目联合</h4><ol>
<li>demo1安装网络请求模块axios</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">cnpm install axios --save<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>修改App.vue,style部分不变</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;div class="all"&gt;
      &lt;div class="one"&gt;
        &lt;div class="onetype" v-for="(item,index) in one" :key="index"&gt;
          &lt;b&gt;{{one[index].name}}&lt;/b&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="twothreefour"&gt;
        &lt;div class="two"&gt;
          &lt;div class="twotype" 
          v-for="(item,index) in two" :key="index"
           @mouseenter="open(index)"&gt;
            &lt;b&gt;{{two[index].name}}&lt;/b&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="threefour" v-if="flag"
           @mouseleave="close()"&gt;
          &lt;div class="threefourtype" v-for="(item,index) in three1" :key="index"&gt;
            &lt;span class="three"&gt;{{three1[index]}}&lt;/span&gt;
            &lt;span class="four" v-for="(item4,index4) in four1" :key="index4"&gt;
{{four1[index4]}}&amp;nbsp;&lt;/span&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;


&lt;script&gt;
import Axios from 'axios';
export default {
  name: 'app',
  data () {
    return {
      one:[],
      two:[],
      three:[],
      four:[],
      flag:false,
      three1:[],
      four1:[]
    }
  },
  methods: {
    getData(){
      const api='http://127.0.0.1:8000/';
      var api1=api+'api/type1/';
      var api2=api+'api/type2/';
      var api3=api+'api/type3/';
      var api4=api+'api/type4/';
      var type1=[];
      var type2=[];
      var type3=[];
      var type4=[];
      Axios.get(api1)
      .then(function (response) {
      // console.log(response);
      for(var i=0;i&lt;response.data.length;i++){
        // console.log(response.data[i])
        type1.push(response.data[i])
      }
      // console.log(type1)
      })
      .catch(function (error) {
      console.log(error);
      });
      this.one=type1;
      Axios.get(api2)
      .then(function (response) {
      // console.log(response);
      for(var i=0;i&lt;response.data.length;i++){
        // console.log(response.data[i])
        type2.push(response.data[i])
      }
      // console.log(type2)
      })
      .catch(function (error) {
      console.log(error);
      });
      this.two=type2;
      Axios.get(api3)
      .then(function (response) {
      // console.log(response);
      for(var i=0;i&lt;response.data.length;i++){
        // console.log(response.data[i])
        type3.push(response.data[i])
      }
      // console.log(type3)
      })
      .catch(function (error) {
      console.log(error);
      });
      this.three=type3;
      Axios.get(api4)
      .then(function (response) {
      // console.log(response);
      for(var i=0;i&lt;response.data.length;i++){
        // console.log(response.data[i])
        type4.push(response.data[i])
      }
      // console.log(type4)
      })
      .catch(function (error) {
      console.log(error);
      });
      this.four=type4;
      // console.log(this.one)
      // console.log(this.two)
      // console.log(this.three)
      // console.log(this.four)
},
    open(index){
      // console.log(this.two[index].id)
      var temp=[]
      for(var i=0;i&lt;this.three.length;i++){
        if(this.three[i].parent===index){
          temp.push(this.three[i].name)
        }
      }
      console.log(temp)
      this.three1=temp;
      var temp4=[]
      for(var j=0;j&lt;this.four.length;j++){
        temp4.push(this.four[j].name)
      }
      this.four1=temp4
      this.flag=true
    },
    close(){
      this.flag=false
    }
  },
  mounted() {
    this.getData()
  },
}
&lt;/script&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-解决跨域问题"><a href="#4-解决跨域问题" class="headerlink" title="4.解决跨域问题"></a>4.解决跨域问题</h4><ol>
<li>安装</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install Django-cors-headers<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'Django.contrib.admin',
    'Django.contrib.auth',
    'Django.contrib.contenttypes',
    'Django.contrib.sessions',
    'Django.contrib.messages',
    'Django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
    'corsheaders'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>setting.py设置</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',#放到中间件顶部
    'Django.middleware.security.SecurityMiddleware',
    'Django.contrib.sessions.middleware.SessionMiddleware',
    'Django.middleware.common.CommonMiddleware',
    'Django.middleware.csrf.CsrfViewMiddleware',
    'Django.contrib.auth.middleware.AuthenticationMiddleware',
    'Django.contrib.messages.middleware.MessageMiddleware',
    'Django.middleware.clickjacking.XFrameOptionsMiddleware',
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>setting中添加</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">CORS_ORIGIN_ALLOW_ALL = True<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="5-使用Django的model实现类别表建立"><a href="#5-使用Django的model实现类别表建立" class="headerlink" title="5.使用Django的model实现类别表建立"></a>5.使用Django的model实现类别表建立</h4><h6 id="四表合一"><a href="#四表合一" class="headerlink" title="四表合一"></a>四表合一</h6><ol>
<li>model中创建新类Type</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class Type(models.Model):
    """
    商品类别
    """
    CATEGORY_TYPE=(
        (1,'一级类目'),
        (2,'二级类目'),
        (3,'三级类目'),
        (4,'四级类目')
    )
    name=models.CharField(default='',max_length=30,verbose_name='类别名',help_text='类别名')
    code=models.CharField(default='',max_length=30,verbose_name='类别code',help_text='类别code')
    desc=models.CharField(default='',max_length=30,verbose_name='类别描述',help_text='类别描述')
    category_type=models.IntegerField(choices=CATEGORY_TYPE,verbose_name='类别描述',help_text='类别描述')
    parent_category=models.ForeignKey('self',null=True,blank=True,verbose_name='父类目录',                                   
help_text='父类别',related_name='sub_cat',on_delete=models.CASCADE)
    is_tab=models.BooleanField(default=False,verbose_name='是否导航',help_text='是否导航')
    class Meta:
        verbose_name='商品类别'
        verbose_name_plural=verbose_name
    def __str__(self):
        return self.name
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>数据更新</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="3">
<li>serializer.py内增加</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from .models import Type
class TypeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model=Type
        fields="__all__"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>views.py中创建视图</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from .models import Type
#导入序列化类
from .serializers import TypeModelSerializer
class TypeView(APIView):
    """
    操作类别表
    """
    renderer_classes = [JSONRenderer]
    def get(self,request,format=None):
        types=Type.objects.all()
        types_serializer = TypeModelSerializer(types, many=True)
        return Response(types_serializer.data)
        def post(self,request):
        name=request.data.get('name')
        category_type=request.data.get('lei')
        parent_category_id=request.data.get('parent')
        type=Type()
        type.name=name
        type.category_type=category_type
        if parent_category_id:
            parent_category=Type.objects.filter(id=parent_category_id).first()
            type.parent_category=parent_category
        type.save()
        type_serializer=TypeModelSerializer(type)
        return Response(type_serializer.data)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>添加路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from app01.views import TypeView
urlpatterns = [
    #......
    path('api/type/',TypeView.as_view())
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>修改</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;script&gt;
import Axios from 'axios';
export default {
  name: 'app',
  data () {
    return {
      type:[],
      one:[],
      two:[],
      flag:false,
      three1:[],
      four1:[]
    }
  },
  methods: {
    getData(){
      const api='http://127.0.0.1:8000/api/type/';
      var _this=this
      
      Axios.get(api)
      .then(function (response) {
        _this.type=response.data;
        for(var i=0;i&lt;_this.type.length;i++){
          if(_this.type[i].category_type===1){
            _this.one.push(_this.type[i])
          } 
        }
        for(var j=0;j&lt;_this.type.length;j++){
          if(_this.type[j].category_type===2){
            _this.two.push(_this.type[j])
          } 
        }
      })
      .catch(function (error) {
      console.log(error);
      });
      
    },
    open(index){
      this.three1=[]
      this.four1=[]
      var parent=this.two[index].id
      for(var i=0;i&lt;this.type.length;i++){
        if(this.type[i].parent_category===parent){
          this.three1.push(this.type[i].name)
        }
        if(this.type[i].category_type===4){
          this.four1.push(this.type[i].name)
        }
      }
      this.flag=true
    },
    close(){
      this.flag=false
    }
  },
  mounted() {
    this.getData()
  }
}
&lt;/script&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="第四章：用户注册认证"><a href="#第四章：用户注册认证" class="headerlink" title="第四章：用户注册认证"></a>第四章：用户注册认证</h2><h4 id="1-初始化前端项目demo3"><a href="#1-初始化前端项目demo3" class="headerlink" title="1.初始化前端项目demo3"></a>1.初始化前端项目demo3</h4><pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;h1&gt;{{title}}&lt;/h1&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      title: 'สืาณ'
    }
  }
}
&lt;/script&gt;
&lt;style&gt;

&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-后端项目"><a href="#2-后端项目" class="headerlink" title="2.后端项目"></a>2.后端项目</h4><ol>
<li>安装依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter pillow django-guardian coreapi<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none"># Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>app01/model.py中重建用户表类，新建key值表类`</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from datetime import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class UserProfile(AbstractUser):
    """
    用户
    """
    is_auther=models.BooleanField(default=False,verbose_name='是否认证')
    phone=models.CharField(max_length=11,verbose_name='电话')
    email = models.CharField(max_length=100,null=True,blank=True,verbose_name='邮箱')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='用户'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.username
class Key(models.Model):
    """
    key表
    """
author=models.ForeignKey(UserProfile,verbose_name='开发者',
on_delete=models.CASCADE)
    app_name=models.CharField(max_length=10,verbose_name='应用名称')
    key=models.CharField(max_length=32,verbose_name='应用key值')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='key表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.key
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>dmoe3/settting.py中加入重建用户表的配置代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">AUTH_USER_MODEL='app01.UserProfile'<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>数据更新命令</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<h4 id="3-前端项目"><a href="#3-前端项目" class="headerlink" title="3.前端项目"></a>3.前端项目</h4><ol>
<li>开发注册用户界面，App.vue</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;h1&gt;{{title}}&lt;/h1&gt;
    &lt;div class="registerwindow"&gt;
      &lt;div class="title"&gt;用户注册&lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;用户名:&lt;/div&gt;
        &lt;input type="text"&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;密码:&lt;/div&gt;
        &lt;input type="text"&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;手机号:&lt;/div&gt;
        &lt;input type="text"&gt;
        &lt;button&gt;获取验证码&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;验证码:&lt;/div&gt;
        &lt;input type="text"&gt;
        &lt;button&gt;确认注册&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      title: '首页',
      codebtn:'获取验证码'
    }
  }
}
&lt;/script&gt;
&lt;style&gt;
*{
  margin:0;
  padding: 0;
  box-sizing: border-box;
}
.registerwindow{
  margin: 0 auto;
  width: 350px;
  height: 200px;
  background: rgba(5, 55, 148, 0.5);
}
.title{
  margin: 0 auto;
  font-size: 30px;
  text-align: center
}
.item{
  margin-top:10px; 
  display: flex;
  flex-direction: row;
}
.text{
  text-align: center;
  width: 80px;
}
input{
  width: 140px;
}
button{
  width: 80px;
  margin-left: 5px;
}
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>前端验证用户信息的逻辑代码,App.vue</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;h1&gt;{{title}}&lt;/h1&gt;
    &lt;div class="registerwindow"&gt;
      &lt;div class="title"&gt;用户注册&lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;用户名:&lt;/div&gt;
        &lt;input type="text" v-model="username"&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;密码:&lt;/div&gt;
        &lt;input type="text" v-model="pwd"&gt;
      &lt;/div&gt;
&lt;div class="item"&gt;
        &lt;div class="text"&gt;邮箱:&lt;/div&gt;
        &lt;input type="text" v-model="email"&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;手机号:&lt;/div&gt;
        &lt;input type="text" v-model="phone"&gt;
        &lt;button :disabled="disabled" @click="authPhone"&gt;{{codebtn}}&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="item"&gt;
        &lt;div class="text"&gt;验证码:&lt;/div&gt;
        &lt;input type="text" v-model="code"&gt;
        &lt;button @click="authUserinfo"&gt;确认注册&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      title: '首页',
      disabled:false,
      time:0,
      codebtn:'获取验证码',
      phone:'',
      username:'',
      pwd:'',
      code:'',
	 email:’’
    }
  },
  methods: {
    getCode(){
      //用来向后台发送请求获取验证码
    },
    goRegister(){
      //提交完整的注册信息
    },
    authPhone(){
      var reg=11 &amp;&amp; /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
      if(this.phone==''){
          alert("请输入手机号码");
      }else if(!reg.test(this.phone)){
          alert("手机格式不正确");
      }else{
          this.time=60;
          this.disabled=true;
          this.timer();
          this.getCode();
      }
    },
    timer() {
      if (this.time &gt; 0) {
            this.time--;
            this.codebtn=this.time+"s";
            setTimeout(this.timer, 1000);
      } else{
            this.time=0;
            this.codebtn="获取验证码";
            this.disabled=false;
      }
    },
    authUserinfo(){
      if(this.username==''){
        alert("用户名不能为空");
      }else if(this.pwd==''){
        alert("密码不能为空");
      }else if(this.phone==''){
        alert("手机号码不能为空");
      }else if(this.code==''){
        alert("验证码不能为空");
      }else{
        this.goRegister();
      }
    }
  }
}
&lt;/script&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-短信对接服务"><a href="#4-短信对接服务" class="headerlink" title="4.短信对接服务"></a>4.短信对接服务</h4><blockquote>
<p>云片：<a target="_blank" rel="noopener" href="https://www.yunpian.com/">https://www.yunpian.com</a></p>
</blockquote>
<ol>
<li>在后端项目目录下新建utils目录，新建yunpian.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">import requests
class YunPian(object):
    def __init__(self,api_key):
        self.api_key=api_key
        self.single_send_url='https://sms.yunpian.com/v2/sms/single_send.json'
    def send_sms(self,code,mobile):
        parmas={
            'apikey':self.api_key,
            'mobile':mobile,
            'text':'【**网】您的验证码是{code}。如非本人操作，请忽略本短信'.format(code=code)
        }
        #text必须要跟云片后台的模板内容 保持一致，不然发送不出去！
        r=requests.post(self.single_send_url,data=parmas)
        print(r)
if __name__=='__main__':
    yun_pian=YunPian('***************（你的apikey）')
    yun_pian.send_sms('***（验证码）','*******（手机号）')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>编写验证相关逻辑,在app01/model.py中新建验证码的表类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class Code(models.Model):
    """
    验证码
    """
    phone=models.CharField(max_length=11,verbose_name='手机号')
    code=models.CharField(max_length=4,verbose_name='验证码')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    end_time = models.DateTimeField(default=datetime.now, verbose_name='过期时间')
    class Meta:
        verbose_name='验证码表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.phone
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>数据更新</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="4">
<li>setting.py中添加代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">#云片网apikey
APIKEY=‘你云片网的apikey’<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="5">
<li>views.py中编写发送验证码的逻辑类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse
import json
import re
import datetime
import random
from demo4.settings import APIKEY
#引入用户表和验证码表
from .models import Code,UserProfile
#引入对接云片网模块
from utils.yunpian import YunPian
#引入drf功能模块
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
class SendCodeView(APIView):
    """
    获取手机验证码
    """
    def get(self,request):
        phone=request.GET.get('phone')
        if phone:
            #验证是否为有效手机号
            mobile_pat = re.compile('^(13\d|14[5|7]|15\d|166|17\d|18\d)\d{8}$')
            res = re.search(mobile_pat, phone)
            if res:
                #如果手机号合法，查看手机号是否被注册过
                had_register=UserProfile.objects.filter(phone=phone)
                if had_register:
                    msg = '手机号已被注册！'
                    result = {"status": "402", "data": {'msg': msg}}
                    return HttpResponse(json.dumps(result, ensure_ascii=False),
                                        content_type="application/json,charset=utf-8")
                else:
                    #检测是否发送过，如果没发送过则发送验证码，如果发送过则另做处理
                    had_send=Code.objects.filter(phone=phone).last()
                    if had_send:
                        #如果这个号码发送过验证码，查看距离上次发送时间间隔有没有达到一分钟
                        if had_send.add_time.replace(tzinfo=None)&gt;
(datetime.datetime.now()-datetime.timedelta(minutes=1)):
                            msg = '距离上次发送验证码不足1分钟！'
                            result = {"status": "403", "data": {'msg': msg}}
                            return HttpResponse(json.dumps(result,ensure_ascii=False),                                             content_type="application/json,charset=utf-8")
                        else:
                            # 发送验证码
                            code = Code()
                            code.phone = phone
                            # 生成验证码
                            c = random.randint(1000, 9999)
                            code.code = str(c)
                            # 设定验证码的过期时间为20分钟以后
                            code.end_time = 
datetime.datetime.now() + datetime.timedelta(minutes=20)
                            code.save()
                            # 调用发送模块
                            code = Code.objects.filter(phone=phone).last().code
                            yunpian = YunPian(APIKEY)
                            sms_status = yunpian.send_sms(code=code, mobile=phone)
                            msg = sms_status
                            return HttpResponse(msg)
                    else:
                        #发送验证码
                        code = Code()
                        code.phone = phone
                        #生成验证码
                        c = random.randint(1000, 9999)
                        code.code = str(c)
                        #设定验证码的过期时间为20分钟以后
                        code.end_time=datetime.datetime.now()+datetime.timedelta(minutes=20)
                        code.save()
                        #调用发送模块
                        code = Code.objects.filter(phone=phone).last().code
                        yunpian = YunPian(APIKEY)
                        sms_status = yunpian.send_sms(code=code, mobile=phone)
                        msg = sms_status
                        # print(msg)
                        return HttpResponse(msg)
            else:
                msg = '手机号不合法！'
                result = {"status": "403", "data": {'msg': msg}}
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json,charset=utf-8")
        else:
            msg = '手机号为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>6.增加路由</p>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import SendCodeView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('sendcode/',SendCodeView.as_view(),name='sendcode')
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>7.解决跨域问题</p>
<pre class="line-numbers language-none"><code class="language-none">pip install django-cors-headers<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
#……
    'app01.apps.App01Config',
    'rest_framework',
    'corsheaders'
]
#......
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',#放到中间件顶部
    'django.middleware.security.SecurityMiddleware',
#……
]
#......
CORS_ORIGIN_ALLOW_ALL = True
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>完善前端验证功能</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;script&gt;
import Axios from 'axios';
export default {
//......
methods: {
    getCode(){
      //用来向后台发送请求获取验证码
      var api='http://127.0.0.1:8000/sendcode/';
      Axios.get(api,{
          params:{
            phone:this.phone
          }
        }  
      )
      .then((Response)=&gt;{
        console.log(Response.data)
        // 根据返回的信息，做出响应的提示
      })
      .catch((error)=&gt;{
        console.log(error)
      })
},
//......
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>完成确认注册功能,views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class RegisterView(APIView):
    """
    注册类
    """
    def get(self,request):
        username=request.GET.get('username')
        pwd=request.GET.get('pwd')
        phone=request.GET.get('phone')
        email=request.GET.get('email')
        code=request.GET.get('code')
        if username:
            pass
        else:
            msg = '用户名不能为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        if pwd:
            pass
        else:
            msg = '密码不能为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        if phone:
            pass
        else:
            msg = '手机号不能为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        if email:
            pass
        else:
            msg = '邮箱不能为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        if code:
            pass
        else:
            msg = '验证码不能为空！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        #查找对比验证码
        code1=Code.objects.filter(phone=phone).last()
        if code==code1:
            #验证验证码是否已经过期
            end_time=code1.end_time
            end_time=end_time.replace(tzinfo=None)
            if end_time &gt; datetime.datetime.now():
                user = UserProfile()
                user.username = username
                user.password = pwd
                user.phone = phone
                user.email=email
                user.save()
                msg = '注册成功！'
                result = {"status": "200", "data": {'msg': msg}}
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json,charset=utf-8")
            else:
                msg = '验证码已过期！'
                result = {"status": "403", "data": {'msg': msg}}
                return HttpResponse(json.dumps(result, ensure_ascii=False),
                                    content_type="application/json,charset=utf-8")
        else:
            msg = '验证码错误！'
            result = {"status": "403", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="10">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import SendCodeView,RegisterView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('sendcode/',SendCodeView.as_view(),name='sendcode'),
    path('register/',RegisterView.as_view(),name='register')
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="11">
<li>前端App.vue注册方法</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">goRegister(){
      //提交完整的注册信息
      var api='http://127.0.0.1:8000/register/';
      Axios.get(api,{
          params:{
            phone:this.phone,
            username:this.username,
            pwd:this.pwd,
            code:this.code,
		   email:this.email
          }
        }
      )
      .then((Response)=&gt;{
        console.log(Response.data)
        // 根据返回的信息，做出响应的提示
      })
      .catch((error)=&gt;{
        console.log(error)
      })
    },
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-邮箱激活功能"><a href="#5-邮箱激活功能" class="headerlink" title="5.邮箱激活功能"></a>5.邮箱激活功能</h4><ol>
<li>setting中增加</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">EMAIL_HOST='smtp.sina.cn'
EMAIL_PORT=25
EMAIL_HOST_USER='xxxxxxxx@sina.cn' #你的邮箱
EMAIL_HOST_PASSWORD='********'
EMAIL_USE_TLS=False
EMAIL_FROM='xxxxxxx1@sina.cn' #同样是你的邮箱，跟上面都是发信者邮箱
#我用的新浪的，也可以用别的
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>model中创建邮箱激活代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class EmailVerifyRecord(models.Model):
    """
    邮箱激活码
    """
    code = models.CharField(max_length=20, verbose_name='激活码')
    email=models.EmailField(max_length=50,verbose_name='邮箱')
    send_time=models.DateTimeField(verbose_name='发送时间',default=datetime.now)
    class Meta:
        verbose_name='邮箱验证码'
        verbose_name_plural=verbose_name
    def __str__(self):
        return '{0}({1})'.format(self.code,self.email)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>更新数据</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="4">
<li>utils目录下新建发送邮件脚本email_send.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from random import Random
from app01.models import EmailVerifyRecord
from django.core.mail import send_mail
from demo4.settings import EMAIL_FROM
def random_str(randomlength=8):
    str=''
    chars='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length=len(chars)-1
    random=Random()
    for i in range(randomlength):
        str+=chars[random.randint(0,length)]
    return str
def send_register_email(email):
    email_record=EmailVerifyRecord()
    code=random_str(16)
    email_record.code=code
    email_record.email=email
    email_record.save()
    email_title='**网注册激活链接'
    email_body='请点击下面的链接激活你的账号：http://127.0.0.1:8000/active/{0}'.format(code)
    send_mail(email_title,email_body,EMAIL_FROM,[email])
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>views.py中新增</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from utils import email_send
class SendActiveCodeView(APIView):
    """
    发送激活链接类
    """
    def get(self,request):
        email=request.GET.get('email')
        if email:
            email_send.send_register_email(email)
            msg = '激活链接已发送都您的邮箱，请前往邮箱完成激活！'
            result = {"status": "200", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        else:
            msg = '未收到邮箱！'
            result = {"status": "404", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
from .models import EmailVerifyRecord
class ActiveView(APIView):
    """
    激活认证用户类
    """
    def get(self,request,code):
        item=EmailVerifyRecord.objects.filter(code=code).last()
        if item:
            email=item.email
            user=UserProfile.objects.filter(email=email).first()
            user.is_auther=True
            user.save()
            msg='已认证为开发者，可以创建应用啦。'
            result = {"status": "200", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
        else:
            msg = '认证失败'
            result = {"status": "403", "data": {'msg': msg}}
            return HttpResponse(json.dumps(result, ensure_ascii=False),
                                content_type="application/json,charset=utf-8")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>增加路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import SendCodeView,RegisterView
from app01.views import SendActiveCodeView,ActiveView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('sendcode/',SendCodeView.as_view(),name='sendcode'),
    path('register/',RegisterView.as_view(),name='register'),
    path('sendactivecode/',SendActiveCodeView.as_view(),name='sendactivecode'),
    path('active/&lt;str:code&gt;',ActiveView.as_view(),name='active')
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>在demo3中增加认证激活代码</li>
</ol>
<ul>
<li>在demo3/src下新建目录components，新建Active.vue组件</li>
<li>父子组件传值，在App.vue中将用户的电子邮件传到子组件Active.vue</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
      &lt;!--…… --&gt;
    &lt;v-active :email='email'&gt;&lt;/v-active&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import Axios from 'axios';
import Active from './components/Active.vue';
export default {
  name: 'app',
  data () {
    return {
      title: '首页',
      disabled:false,
      time:0,
      codebtn:'获取验证码',
      phone:'',
      username:'',
      pwd:'',
      code:'',
      email:''
    }
  },
  components:{
    'v-active':Active
  },
//......
}
&lt;/script&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>在active中编写</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
    &lt;div&gt;
        &lt;h1&gt;{{title}}&lt;/h1&gt;
        &lt;button @click="sendcode"&gt;认证激活&lt;/button&gt;
    &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import Axios from 'axios';
export default {
    data () {
    return {
      title: '认证激活组件',
    }
  },
  props:['email'],
  methods: {
      sendcode(){
        //   alert(this.email)
                var api='http://127.0.0.1:8000/sendactivecode/';
            Axios.get(api,{
                params:{
                    email:this.email
                    }
                }  
            )
            .then((Response)=&gt;{
                console.log(Response.data)
                // 根据返回的信息，做出响应的提示
            })
            .catch((error)=&gt;{
                console.log(error)
            })
      }
  },
}
&lt;/script&gt;
&lt;style&gt;
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="第五章：token登录"><a href="#第五章：token登录" class="headerlink" title="第五章：token登录"></a>第五章：token登录</h2><h4 id="1-django中使用Cookie"><a href="#1-django中使用Cookie" class="headerlink" title="1.django中使用Cookie"></a>1.django中使用Cookie</h4><ol>
<li>创建项目demo5，新建app01</li>
<li>model.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
# Create your models here.
class Administrator(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>执行数据更新命令</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="4">
<li>在templates目录下新建login.html</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
    &lt;style&gt;
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form action="login.html" method="post"&gt;
        &lt;div&gt;
            &lt;label for="user"&gt;用户名：&lt;/label&gt;
            &lt;input id="user" type="text" name="user" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label for="pwd"&gt;密码：&lt;/label&gt;
            &lt;input id="pwd" type="password" name="pwd" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label&gt; &lt;/label&gt;
            &lt;input type="submit" value="登录" /&gt;
            &lt;span style="color: red;"&gt;{{ msg }}&lt;/span&gt;
        &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>在templates目录下新建index.html</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Hello {{ username }}&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>在setting.py中添加路径设置代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>在setting.py中注释掉csrf的验证中间件</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,redirect,HttpResponse
from .models import Administrator
# Create your views here.
#自定义登录函数视图
def login(request):
    message = ""
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        c = Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            rep = redirect('index.html')
            rep.set_cookie('username', user)
            rep.set_cookie('password', pwd)
            return rep
        else:
            message = "用户名或密码错误"
    return render(request,'login.html', {'msg': message})
#访问首页视图函数
def index(request):
    # 如果用户已经登录，获取当前登录的用户名
    # 否则，返回登录页面
    username = request.COOKIES.get('username')
    password = request.COOKIES.get('password')
    c = Administrator.objects.filter(username=username, password=password).count()
    if c:
        return render(request, 'index.html', {'username': username})
    else:
        return redirect('/login.html')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>添加路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import login,index
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login.html', login),
    path('index.html', index),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="10">
<li>改写为加密的逻辑</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">def login(request):
    message = ""
    if request.method == "POST":
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        c = Administrator.objects.filter(username=user, password=pwd).count()
        if c:
			#加密
            rep = redirect('index.html')
            rep.set_signed_cookie('username', user)
            rep.set_signed_cookie('password', pwd)
            return rep
        else:
            message = "用户名或密码错误"
    return render(request,'login.html', {'msg': message})
def index(request):
    # 如果用户已经登录，获取当前登录的用户名
    # 否则，返回登录页面
    username = request.get_signed_cookie('username')
    password = request.get_signed_cookie('password')
    c = Administrator.objects.filter(username=username, password=password).count()
    if c:
        return render(request, 'index.html', {'username': username})
    else:
        return redirect('/login.html')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-django中使用Session"><a href="#2-django中使用Session" class="headerlink" title="2.django中使用Session"></a>2.django中使用Session</h4><ol>
<li>setting</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">SESSION_ENGINE = 'django.contrib.sessions.backends.db'  # 引擎（默认）
SESSION_COOKIE_NAME="sessionid"  # Session的Cookie保存在浏览器上时的key
SESSION_COOKIE_PATH="/"              # Session的Cookie保存的路径（默认）
SESSION_COOKIE_DOMAIN = None             # Session的Cookie保存的域名（默认）
SESSION_COOKIE_SECURE = False          # 是否Https传输Cookie（默认）
SESSION_COOKIE_HTTPONLY = True        # 是否Session的Cookie只支持http传输（默认）
SESSION_COOKIE_AGE = 1209600             # Session的Cookie失效日期（2周）（默认）
SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # 是否关闭浏览器使得Session过期（默认）
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session默认修改之后才保存
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,redirect,HttpResponse
from .models import Administrator
# Create your views here.
def login(request):
    message = ""
    if request.method == "POST":
        request.session['is_login'] = True
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        c = Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            request.session['is_login'] = True
            request.session['username'] = user
            rep = redirect('/index.html')
            return rep
        else:
            message = "用户名或密码错误"
    return render(request,'login.html', {'msg': message})
def auth(func):
    def inner(request, *args, **kwargs):
        is_login = request.session.get('is_login')
        if is_login:
            return func(request, *args, **kwargs)
        else:
            return redirect('/login.html')
    return inner
@auth
def index(request):
    # 如果用户已经登录，获取当前登录的用户名
    # 否则，返回登录页面
    print(666)
    username = request.session.get('username')
    c = Administrator.objects.filter(username=username).count()
    if c:
        return render(request, 'index.html', {'username': username})
    else:
        return redirect('/login.html')
def logout(request):
    request.Session.clear()
    return redirect('/login.html')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>3.添加路由</p>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import login,index,logout
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login.html', login),
    path('index.html', index),
    path('logout.html', logout),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>改造index.html</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Hello {{ username }}&lt;/h1&gt;
    &lt;a href="/logout.html"&gt;注销&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-Django实现Token登录的业务模式"><a href="#3-Django实现Token登录的业务模式" class="headerlink" title="3.Django实现Token登录的业务模式"></a>3.Django实现Token登录的业务模式</h4><ol>
<li>在django中安装依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>setting,py注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
    'rest_framework.authtoken'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ol start="3">
<li>更新数据</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="4">
<li>创建超级用户</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py createsuperuser<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>配置登录的路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework.authtoken import views
urlpatterns = [
    #……
#drf自带的token认证模式
    path('api-token-auth/', views.obtain_auth_token),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>setting.py中添加配置代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated', #必须有
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>views.py重写</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,redirect,HttpResponse
from rest_framework.views import APIView
# Create your views here.
class IndexView(APIView):
    """
    สืาณ
    """
    # authentication_classes = []
    # permission_classes = []
    def get(self,request):
        # print(request)
        return HttpResponse('首页')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>url.py重写</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from rest_framework.authtoken import views
from app01.views import IndexView
urlpatterns = [
    path('admin/', admin.site.urls),
#drf自带的token认证模式
    path('api-token-auth/', views.obtain_auth_token),
    path('index/',IndexView.as_view(),name='index'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>取消认证限制</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,redirect,HttpResponse
from rest_framework.views import APIView
# Create your views here.
class IndexView(APIView):
    """
    สืาณ
    """
    authentication_classes = []
    permission_classes = []
    def get(self,request):
        # print(request)
        return HttpResponse('สืาณ')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-JWT在Django中的应用"><a href="#4-JWT在Django中的应用" class="headerlink" title="4.JWT在Django中的应用"></a>4.JWT在Django中的应用</h4><ol>
<li>新建demo5_jwt,新建app01</li>
<li>安装依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>setting中注册代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>安装JWT依赖包</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework-jwt<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>追加配置相关代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated', #必须有
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    )
}
import datetime
JWT_AUTH = {
 # 指明token的有效期
 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path('admin/', admin.site.urls),
#jwt的认证接口
    path('jwt-token-auth/', obtain_jwt_token),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>更新数据,创建超级用户</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>views.py身份验证类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,redirect,HttpResponse
from rest_framework.views import APIView
# Create your views here.
class IndexView(APIView):
    """
    สืาณ
    """
    # authentication_classes = []
    # permission_classes = []
    def get(self,request):
        print(request)
        return HttpResponse('首页')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>添加路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
from app01.views import IndexView
urlpatterns = [
    path('admin/', admin.site.urls),
#jwt的认证接口
    path('jwt-token-auth/', obtain_jwt_token),
    path('index/',IndexView.as_view(),name='index')
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="第六章：实现VIP模式"><a href="#第六章：实现VIP模式" class="headerlink" title="第六章：实现VIP模式"></a>第六章：实现VIP模式</h2><h4 id="1-权限管理雏形演示"><a href="#1-权限管理雏形演示" class="headerlink" title="1.权限管理雏形演示"></a>1.权限管理雏形演示</h4><ol>
<li>新建demo6，创建app01</li>
<li>建立权限表和用户表</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
# Create your models here.
class Permission(models.Model):
    """
    权限表
    """
    url=models.CharField(max_length=64)
    title=models.CharField(max_length=10)
    class Meta:
        verbose_name='权限表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class Userinfor(models.Model):
    """
    用户表
    """
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    permission = models.ManyToManyField(Permission ,null=True,blank=True)
    class Meta:
        verbose_name = '用户表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>数据更新并且创建超级用户</li>
<li>admin.py注册表</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from .models import Permission,Userinfor
# Register your models here.
admin.site.register(Permission)
admin.site.register(Userinfor)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>views.py编写登录，访问，查看用户逻辑</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse,redirect
from .models import Userinfor,Permission
# Create your views here.
def login(request):
    if request.method == "POST":
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=Userinfor.objects.filter(name=username,pwd=pwd).first()
        if user:
            #验证身份
            request.session["user_id"]=user.pk
            return HttpResponse('登录成功')
    return render(request, "login.html")
def userinfo(request):
    #首先进行身份验证
    pk=request.session.get('user_id')
    if not pk:
        return redirect("/login/")
    #然后进行权限验证
    user=Userinfor.objects.filter(id=pk).first()
    p_list = []
    p_queryset = user.permission.all()
    #获取用户的权限列表
    for p in p_queryset:
        p_list.append(p.url)
    #去重
    p_list=list(set(p_list))
    # print(p_list)
    # 获取URL
    c = request.path_info
    if c in p_list:
        u_queryset=Userinfor.objects.all()
        return render(request,"userinfo.html",{ "u_queryset":u_queryset})
    else:
        return HttpResponse('没有权限访问该页面')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import login,userinfo
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', login),
    path('userinfo01/', userinfo),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>templates目录下新建login.html</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h4&gt;用户登录&lt;/h4&gt;
&lt;form action="/login/" method="post"&gt;
    {% csrf_token %}
    用户名：&lt;input type="text" name="username"&gt;
    密码：&lt;input type="password" name="pwd"&gt;
    &lt;input type="submit"&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>templates目录下新建userinfo.html</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;Title&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h4&gt;用户&lt;/h4&gt;
&lt;ul&gt;
   {% for user in u_queryset %}
    &lt;li&gt;{{ user.name }}&lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;

&lt;/body&gt;
&lt;/html&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-django项目中使用RBAC"><a href="#2-django项目中使用RBAC" class="headerlink" title="2.django项目中使用RBAC"></a>2.django项目中使用RBAC</h4><ol>
<li>demo6中新建App，命名为rbac</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py startapp rbac<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="2">
<li>在setting添加注册代码（和注册app一样）</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">'RBAC.apps.RBACConfig'<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>rbac中新建model.py权限管理所需要的表类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
# Create your models here.
class Permission(models.Model):
    """
    权限表
    """
    url=models.CharField(max_length=64)
    title=models.CharField(max_length=10)
    class Meta:
        verbose_name='权限表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class Role(models.Model):
    """
    角色表
    """
    title=models.CharField(max_length=10)
    permission=models.ManyToManyField(Permission,null=True,blank=True)
    class Meta:
        verbose_name='角色表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class User(models.Model):
    """
    用户表
    """
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    role = models.ManyToManyField(Role,null=True,blank=True)
    class Meta:
        verbose_name = '用户表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.name
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>在rbac/admin写入注册代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from .models import User,Role,Permission
# Register your models here.
admin.site.register(Permission)
admin.site.register(Role)
admin.site.register(User)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>数据更新</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="6">
<li>重写登录验证逻辑</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import login
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', login),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>app01/view.py重写</li>
</ol>
<ul>
<li>写法一</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse,redirect
from RBAC.models import User,Permission,Role
# Create your views here.
def login(request):
    if request.method == "POST":
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=User.objects.filter(name=username,pwd=pwd).first()
        if user:
            #验证身份
            request.session["user_id"]=user.pk
            #查询角色
            ret=user.role.all()
            print(ret)#&lt;QuerySet [&lt;Role: 人力资源总监&gt;]&gt;
            #查询角色所对应的权限
            re=user.role.all().values('permission__url')
            print(re)#&lt;QuerySet [{'permission__url': '/users/'}]&gt;
            permission_list=[]
            for item in re:
                permission_list.append(item["permission__url"])
            print(permission_list)#['/users/']
            request.session["permission_list"] = permission_list
            return HttpResponse('登录成功')
    return render(request, "login.html")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>写法二</li>
</ul>
<pre class="line-numbers language-none"><code class="language-none">def login(request):
    if request.method == "POST":
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=User.objects.filter(name=username,pwd=pwd).first()
        if user:
            #验证身份
            request.session["user_id"]=user.pk
            #查询角色
            ret=user.role.all()
            # print(ret)#&lt;QuerySet [&lt;Role: 人力资源总监&gt;]&gt;
            #查询角色所对应的权限
            permission_list = []
            for item1 in ret:
                #多对多连表查询
                rep =Permission.objects.filter(role__title=item1)
                for item2 in rep:
                    # print(item2.url)#/users/
                    permission_list.append(item2.url)
            print(permission_list)
            request.session["permission_list"] = permission_list
           
  return HttpResponse('登录成功')
    return render(request, "login.html")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="8">
<li>权限验证，在app01/views.py中编写查看用户函数</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">import re
def user(request):
    #获取session键值，如果不存在不报错，返回None
    permission_list=request.session.get('permission_list',[])
    # print(permission_list)
    path=request.path_info
    # print(path)
    flag=False
    for permission in permission_list:
        permission="^%s$"%permission
        ret=re.match(permission,path)
        if ret:
            flag=True
            break
    # print(flag)
    if not flag:
        return HttpResponse('无访问权限！')
    return HttpResponse('查看用户')
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import login,user
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', login),
    path('users/', user),
]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-Django基于中间件的权限验证"><a href="#3-Django基于中间件的权限验证" class="headerlink" title="3.Django基于中间件的权限验证"></a>3.Django基于中间件的权限验证</h4><p>1.在rbac下新建包service，在service目录下新建rbac.py</p>
<pre class="line-numbers language-none"><code class="language-none">import re
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class ValidPermission(MiddlewareMixin):
    """
    权限验证中间件类
    """
    def process_request(self,request):
        ######################中间件内容start###############
        # 获取session键值，如果不存在不报错，返回[]
        permission_list = request.session.get('permission_list', [])
        # print(permission_list)
        path = request.path_info
        # print(path)
        flag = False
        for permission in permission_list:
            permission = "^%s$" % permission
            ret = re.match(permission, path)
            if ret:
                flag = True
                break
        # print(flag)
        if not flag:
            return HttpResponse('无访问权限！')
        ##################中间件内容end###################
        return None
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>setting内配置中间件</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'RBAC.service.RBAC.ValidPermission'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>设置白名单,修改rbac/service/rbac.py为</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">import re
from django.shortcuts import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class ValidPermission(MiddlewareMixin):
    """
    权限验证中间件类
    """
    def process_request(self,request):
        ######################中间件内容start###############
        path = request.path_info
        # print(path)
        #查看是否属于白名单
        # valid_url_list=['/login/','/register/','/admin/.*']
        # for valid_url in valid_url_list:
        #     ret=re.match(valid_url,path)
        #     if ret:
        #         return None
        # 获取session键值，如果不存在不报错，返回None
        permission_list = request.session.get('permission_list', [])
        # print(permission_list)
        flag = False
        for permission in permission_list:
            permission = "^%s$" % permission
            ret = re.match(permission, path)
            if ret:
                flag = True
                break
        # print(flag)
        if not flag:
            return HttpResponse('无访问权限！')
        ##################中间件内容end###################
        return None
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>解耦,app01/views.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">def login(request):
#登录函数
    if request.method == "POST":
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=User.objects.filter(name=username,pwd=pwd).first()
        if user:
            #验证身份
            request.session["user_id"]=user.pk
            #查询角色
            ret=user.role.all()
            # print(ret)#&lt;QuerySet [&lt;Role: 人力资源总监&gt;]&gt;
            #查询角色所对应的权限
            permission_list = []
            for item1 in ret:
                #多对多连表查询
                rep =Permission.objects.filter(role__title=item1)
                for item2 in rep:
                    # print(item2.url)#/users/
                    permission_list.append(item2.url)
            # print(permission_list)
            request.session["permission_list"] = permission_list
            return HttpResponse('登录成功')
    return render(request, "login.html")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>rbac/service下新建permission.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from RBAC.models import User,Permission,Role
def initial_permission(user,request):
    # 查询角色
    ret = user.role.all()
    # print(ret)#&lt;QuerySet [&lt;Role: 人力资源总监&gt;]&gt;
    # 查询角色所对应的权限
    permission_list = []
    for item1 in ret:
        # 多对多连表查询
        rep = Permission.objects.filter(role__title=item1)
        for item2 in rep:
            # print(item2.url)#/users/
            permission_list.append(item2.url)
    # print(permission_list)
    request.session["permission_list"] = permission_list
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>将app01/views.py中的login函数改写为</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse,redirect
from RBAC.models import User,Permission,Role
# Create your views here.
from RBAC.service.permission import initial_permission
def login(request):
    if request.method == "POST":
        username=request.POST.get('username')
        pwd=request.POST.get('pwd')
        user=User.objects.filter(name=username,pwd=pwd).first()
        if user:
            #验证身份
            request.session["user_id"]=user.pk
            initial_permission(user,request)
            return HttpResponse('登录成功')
    return render(request, "login.html")
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-Django-REST-framework实现权限管理"><a href="#4-Django-REST-framework实现权限管理" class="headerlink" title="4.Django REST framework实现权限管理"></a>4.Django REST framework实现权限管理</h4><ol>
<li>新建demo6_drf,新建app01</li>
<li>model中新建相关表类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
from datetime import datetime
# Create your models here.
class UserInfo(models.Model):
    """
    用户表
    """
    user_type_chioces=(
        (1,"普通用户"),
        (2,"VIP"),
        (3,"SVIP"),
    )
    user_type=models.IntegerField(choices=user_type_chioces)
    username=models.CharField(max_length=32)
    password=models.CharField(max_length=64)
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='用户表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.username
class UserToken(models.Model):
    """
    token表
    """
    user=models.ForeignKey(UserInfo,on_delete=models.CASCADE)
    token=models.CharField(max_length=64)
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='token表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.user.username
class CommonVideo(models.Model):
    """
    普通视频
    """
    title=models.CharField(max_length=32)
    url=models.CharField(max_length=200,verbose_name='资源地址')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='普通视频表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class VIPVideo(models.Model):
    """
    会员视频
    """
    title=models.CharField(max_length=32)
    url=models.CharField(max_length=200,verbose_name='资源地址')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='会员视频表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class SVIPVideo(models.Model):
    """
    超级会员视频
    """
    title=models.CharField(max_length=32)
    url=models.CharField(max_length=200,verbose_name='资源地址')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='超级会员视频表'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>数据更新</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="4">
<li>安装drf相关依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>setting中注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'rest_framework'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>views.py编写用户登录逻辑代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from .models import *
# Create your views here.
def md5(user):
    import hashlib
    import time
    ctime=str(time.time())
    m=hashlib.md5(bytes(user,encoding='utf-8'))
    m.update(bytes(ctime,encoding='utf-8'))
    return m.hexdigest()
class AuthView(APIView):
    """
    登录
    """
    def post(self,request):
        ret={'code':1000,'msg':'登录成功！'}
        try:
            user=request._request.POST.get('username')
            pwd=request._request.POST.get('password')
            obj=UserInfo.objects.filter(username=user,password=pwd).first()
            if not obj:
                ret['code']=1001
                ret['msg']='用户名或密码错误'
                return JsonResponse(ret)
            #为登录用户创建token
            token=md5(user)
            #存在则更新，不存在的创建
            UserToken.objects.update_or_create(user=obj,defaults={'token':token})
            ret['token']=token
        except Exception as e:
            ret['code']=1002
            ret['msg']='请求异常'
        return JsonResponse(ret)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
from app01.views import AuthView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/',AuthView.as_view(),name='auth'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-为demo6-drf添加身份验证功能"><a href="#5-为demo6-drf添加身份验证功能" class="headerlink" title="5.为demo6_drf添加身份验证功能"></a>5.为demo6_drf添加身份验证功能</h4><ol>
<li>app01目录下新建serializer.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers
#引入数据表类
from .models import CommonVideo,VIPVideo,SVIPVideo
#将三个数据表类进行序列化 
class CommonVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model=CommonVideo
        fields = "__all__"
class VIPVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model=VIPVideo
        fields = "__all__"
class SVIPVideoSerializer(serializers.ModelSerializer):
    class Meta:
        model=SVIPVideo
        fields = "__all__"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>app01下编写认证类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from rest_framework.views import APIView
#引入所有数据表
from .models import *
引入所有序列化类
from .serializers import *
#引入drf相关模块
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
from rest_framework import exceptions
# Create your views here.
class Authtication(object):
    def authenticate(self,request):
        # 验证是否已经登录,函数名必须为：authenticate
        token = request._request.GET.get('token')
        token_obj=UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败。')
        #在rest_framework内部会将以下两个元素赋值到request，以供后续使用
        return (token_obj.user,token_obj)
    def authenticate_header(self,request):
        #这个函数可以没内容，但是必须要有
        pass
class CommonVideoView(APIView):
    """
    登录后即可访问的内容资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    authentication_classes = [Authtication,]
    def get(self,request):
        # print(request.user,request.auth)#user1 user1
        video_list = CommonVideo.objects.all()
        re = CommonVideoSerializer(video_list, many=True)
        return Response(re.data)
#…………
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">#бнбн
from app01.views import AuthView,CommonVideoView
urlpatterns = [
    #бнбн
    path('common/',CommonVideoView.as_view(),name='common'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>解耦。把认证类和视图逻辑类分开。app01下创建utils目录，在下创建auth.py,把Authication类代码迁移到auth.py中</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from ..models import *
from rest_framework import exceptions
class Authtication(object):
    def authenticate(self,request):
        # 验证是否已经登录,函数名必须为：authenticate
        token = request._request.GET.get('token')
        token_obj=UserToken.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败。')
        #在rest_framework内部会将以下两个元素赋值到request，以供后续使用
        return (token_obj.user,token_obj)
    def authenticate_header(self,request):
        #这个函数可以没内容，但是必须要有
        pass
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>在views.py中添加引入代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from .utils.auth import Authtication<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="6">
<li>全局身份验证配置，setting中追加</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'app01.utils.auth.Authtication',
    )
}
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>views.py中的登录类设置代码，使其不受全局身份验证的影响</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class AuthView(APIView):
    """
    登录
    """
    authentication_classes = []
    def post(self,request):
	#……
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="6-为demo6-drf添加权限管理功能"><a href="#6-为demo6-drf添加权限管理功能" class="headerlink" title="6.为demo6_drf添加权限管理功能"></a>6.为demo6_drf添加权限管理功能</h4><ol>
<li>在app01/utils/auth.py内添加VIP和SVIP权限验证代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">class VIP(object):
	“””
	验证VIP权限
	“””
    def has_permission(self,request,view):
        if request.user.user_type&lt;2:
            return False
        return True
class SVIP(object):
	“””
	验证SVIP权限
	“””
    def has_permission(self,request,view):
        if request.user.user_type&lt;3:
            return False
        return True
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>在app01/views.py中新增获取VIP资源和SVIP资源的视图函数</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">#……
from .utils.auth import VIP,SVIP
# Create your views here.
#……
class VIPVideoView(APIView):
    """
    vip可访问的资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    permission_classes = [VIP]
    def get(self,request):
        video_list = VIPVideo.objects.all()
        re = VIPVideoSerializer(video_list, many=True)
        return Response(re.data)
class SVIPVideoView(APIView):
    """
    vip可访问的资源
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    permission_classes = [SVIP]
    def get(self,request):
        video_list = SVIPVideo.objects.all()
        re = SVIPVideoSerializer(video_list, many=True)
        return Response(re.data)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>新增路由代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
#引入相关的视图类
from app01.views import AuthView,CommonVideoView,VIPVideoView,SVIPVideoView
urlpatterns = [
path('admin/', admin.site.urls),
#登录验证
path('auth/',AuthView.as_view(),name='auth'),
#获取普通资源
path('common/',CommonVideoView.as_view(),name='common'),
#获取VIP资源
path('vip/',VIPVideoView.as_view(),name='vip'),
#获取SVIP资源
    path('svip/',SVIPVideoView.as_view(),name='svip'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="第七章：违禁词审查功能"><a href="#第七章：违禁词审查功能" class="headerlink" title="第七章：违禁词审查功能"></a>第七章：违禁词审查功能</h2><h4 id="1-模糊搜索的后端逻辑"><a href="#1-模糊搜索的后端逻辑" class="headerlink" title="1.模糊搜索的后端逻辑"></a>1.模糊搜索的后端逻辑</h4><ol>
<li>创建demo7，新建app01</li>
<li>安装依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>setting.py中添加注册代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    #бнбн
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>更新数据</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<ol start="5">
<li>model.py新建表类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime
# Create your models here.
class UserProfile(AbstractUser):
    """
    用户表
    """
    user_type_chioces = (
        (1, "普通用户"),
        (2, "版主"),
        (3, "管理员"),
    )
    level = models.IntegerField(choices=user_type_chioces,default=1)
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='用户'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.username
class Article(models.Model):
    """
    文章表
    """
    title=models.CharField(max_length=30,verbose_name='标题')
    content=models.CharField(max_length=5000,verbose_name='文章内容')
    user=models.ForeignKey(UserProfile,on_delete=models.CASCADE)
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='文章'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="6">
<li>setting配置用户表的继承代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">AUTH_USER_MODEL='app01.UserProfile'<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="7">
<li>数据更新,创建超级用户</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser
Username: root
邮箱:
Password:
Password (again):
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>8.app01/admin.py中注册表</p>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from .models import UserProfile,Article
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Article)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="2-实现模糊搜索前端逻辑"><a href="#2-实现模糊搜索前端逻辑" class="headerlink" title="2.实现模糊搜索前端逻辑"></a>2.实现模糊搜索前端逻辑</h4><ol>
<li>创建项目demo7_1，并安装好依赖</li>
<li>修改demo7_1/src/App.vue</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;div class="search"&gt;
      关键词：&lt;input type="text"&gt;&lt;button&gt;搜索&lt;/button&gt;
    &lt;/div&gt;
    &lt;div class="list"&gt;
      &lt;div class="article"&gt;
        &lt;div class="title"&gt;标题&lt;/div&gt;
        &lt;div class="content"&gt;内容内容内容内容内容内容内容内容内容&lt;/div&gt;
      &lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      keyword: '',
      article:[]
    }
  },
  methods:{ 
  }
}
&lt;/script&gt;
&lt;style&gt;
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="3-开发模糊搜索功能"><a href="#3-开发模糊搜索功能" class="headerlink" title="3.开发模糊搜索功能"></a>3.开发模糊搜索功能</h4><ol>
<li>在demo7/app01下新建serializers.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers
#引入文章表和用户表
from .models import UserProfile,Article
class UserProfileSerializer(serializers.ModelSerializer):
	“””
	序列化用户表
	“””
    class Meta:
        model=UserProfile
        fields = "__all__"
class ArticleSerializer(serializers.ModelSerializer):
	“””
	序列化文章类
	“””
    class Meta:
        model=Article
        fields = "__all__"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>app01/views.py中编写对应的模糊搜素代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render
#引入APIview
from rest_framework.views import APIView
#引入用户数据表类
from .models import UserProfile,Article
#引入序列化类
from .serializers import UserProfileSerializer,ArticleSerializer
#引入drf功能模块
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
#引入Q模块
from django.db.models import Q
# Create your views here.
class GetArticleViews(APIView):
    """
    获取文章列表
    """
    def get(self,request):
        keyword=request._request.GET.get('keyword')
        # print(keyword)
        if keyword:
            article_list = Article.objects.filter(Q(title__icontains=keyword)|Q(content__icontains=keyword))
        else:
            article_list = Article.objects.all()
        re = ArticleSerializer(article_list, many=True)
        return Response(re.data)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
#引入模糊搜索相关视图类
from app01.views import GetArticleViews
urlpatterns = [
path('admin/', admin.site.urls),
#搜索文章路由
    path('getlist/',GetArticleViews.as_view(),name='getlist'),
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>安装跨域模块</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install django-cors-headers<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework',
    'corsheaders'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',#放到中间件顶部
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">CORS_ORIGIN_ALLOW_ALL = True<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>运行demo7</li>
<li>在demo7_1下安装axios</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">cnpm install axios --save<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="7">
<li>demo7_1/src/App.vue中加入后端提交关键词的功能</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
    &lt;div class="search"&gt;
      关键词：&lt;input type="text" v-model="keyword"&gt;&lt;button @click="GetList()"&gt;搜索&lt;/button&gt;
    &lt;/div&gt;
    &lt;div class="list"&gt;
      &lt;div class="article" v-for="(item,index) in article" :key=index&gt;
        &lt;div class="title"&gt;{{item.title}}&lt;/div&gt;
        &lt;div class="content"&gt;{{item.content}}&lt;/div&gt;
      &lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
//引入axios模块
import Axios from 'axios';
export default {
  name: 'app',
  data () {
    return {
      keyword: '',
      article:[]
    }
  },
  methods:{
//向后端提交关键词
    GetList(){
      var api='http://127.0.0.1:8000/getlist/?keyword='+this.keyword
      console.log(api)
      Axios.get(api)
      .then((response)=&gt;{
        console.log(response);
        this.article=response.data
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
    }
  }
}
&lt;/script&gt;
&lt;style&gt;
*{
  box-sizing: border-box;
}
.search{
  margin:0 auto;
  margin-top: 100px;
  width: 300px;
}
.article{
  width: 300px;
  margin:0 auto;
  margin-top: 20px;
  border: 2px solid;
  padding: 5px;
}
.title{
  border-bottom: 2px dashed royalblue;
}
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="4-开发违禁词自审功能后端逻辑"><a href="#4-开发违禁词自审功能后端逻辑" class="headerlink" title="4.开发违禁词自审功能后端逻辑"></a>4.开发违禁词自审功能后端逻辑</h4><ol>
<li>新建demo7_2项目，创建app01</li>
<li>安装依赖</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install djangorestframework markdown django-filter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="3">
<li>注册</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
    'rest_framework'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>新建表类</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.db import models
from django.contrib.auth.models import AbstractUser
from datetime import datetime
# Create your models here.
class UserProfile(AbstractUser):
    """
    用户表
    """
    user_type_chioces = (
        (1, "普通用户"),
        (2, "版主"),
        (3, "管理员"),
    )
    level = models.IntegerField(choices=user_type_chioces,default=1)
    is_frozen=models.BooleanField(default=False,verbose_name='是否被冻结')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='用户'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.username
class Article(models.Model):
    """
    文章表
    """
    title=models.CharField(max_length=30,verbose_name='标题')
    content=models.CharField(max_length=5000,verbose_name='文章内容')
    user=models.ForeignKey(UserProfile,on_delete=models.CASCADE)
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='文章'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.title
class Comment(models.Model):
    """
    评论表
    """
    user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    article=models.ForeignKey(Article,on_delete=models.CASCADE)
    content = models.CharField(max_length=150, verbose_name='评论内容')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name='评论'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.content
class Card(models.Model):
    """
    违禁词库
    """
    word = models.CharField(max_length=150, verbose_name='违禁词')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')
    class Meta:
        verbose_name = '违禁词'
        verbose_name_plural = verbose_name
    def __str__(self):
        return self.word
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="5">
<li>setting中配置用户表的继承代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">AUTH_USER_MODEL='app01.UserProfile'<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="6">
<li>执行数据更新命令，创建超级用户</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">python manage.py makemigrations
python manage.py migrate

python manage.py createsuperuser
Username: root
邮箱:
Password:
Password (again):

<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="7">
<li>在app01/admin.py中注册表</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from .models import UserProfile,Article,Comment,Card
# Register your models here.
admin.site.register(UserProfile)
admin.site.register(Article)
admin.site.register(Comment)
admin.site.register(Card)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="5-开发违禁词自审查功能的前端逻辑"><a href="#5-开发违禁词自审查功能的前端逻辑" class="headerlink" title="5.开发违禁词自审查功能的前端逻辑"></a>5.开发违禁词自审查功能的前端逻辑</h4><ol>
<li>创建demo7_3,并且安装好依赖</li>
<li>App.vue中初始化代码</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
      &lt;div class="userinfo"&gt;
        用户名：{{username}}
      &lt;/div&gt;
      &lt;div class="login" v-if="flag"&gt;
        &lt;input type="text" v-model="username"&gt;
        &lt;input type="text" v-model="pwd"&gt;
        &lt;button&gt;登录&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="article"&gt;
        &lt;div class="title"&gt;文章标题&lt;/div&gt;
        &lt;div class="content"&gt;文章内容&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="makecomment"&gt;
        &lt;div&gt;评论内容&lt;input type="text" v-model="comment"&gt;&lt;/div&gt;
        &lt;button&gt;提交评论&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="commentlist"&gt;
        &lt;div class="commentcontent"&gt;评论内容&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="makearticle"&gt;
        &lt;div class="title"&gt;文章标题 &lt;input type="text" v-model="title"&gt; &lt;/div&gt;
        &lt;div class="content"&gt;文章内容 &lt;input type="text" v-model="content"&gt; &lt;/div&gt;
        &lt;button&gt;提交文章&lt;/button&gt;
      &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  name: 'app',
  data () {
    return {
      username: 'root',
      pwd:'',
      flag:true,
      article:[],
      title:'',
      comment:''
    }
  }
}
&lt;/script&gt;

&lt;style&gt;
.userinfo{
  width: 300px;
  margin: 0 auto;
}
.login{
  width: 300px;
  margin: 0 auto;
}
.login input{
  width: 200px;
  margin: 0 auto;
}
.article{
  width: 300px;
  margin: 0 auto;
}
.makecomment{
  width: 300px;
  margin: 0 auto;
}
.commentlist{
  width: 300px;
  margin: 0 auto;
}
.makearticle{
  width: 300px;
  margin: 0 auto;
}
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h4 id="6-违禁词自审查功能开发"><a href="#6-违禁词自审查功能开发" class="headerlink" title="6.违禁词自审查功能开发"></a>6.违禁词自审查功能开发</h4><ol>
<li>demo7_2/app01下新建序列化文件serializers.py</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from rest_framework import serializers
#引入用户表、文章表、评论表、关键词表
from .models import UserProfile,Article,Comment,Card
class UserProfileSerializer(serializers.ModelSerializer):
	“””
	序列化用户表
	“””
    class Meta:
        model=UserProfile
        fields = "__all__"
class CommentSerializer(serializers.ModelSerializer):
	“””
	序列化评论表
	“””
    class Meta:
        model=Comment
        fields = "__all__"
class ArticleSerializer(serializers.ModelSerializer):
	“””
	序列化文章表
	“””
    class Meta:
        model=Article
        fields = "__all__"
class CardSerializer(serializers.ModelSerializer):
	“””
	序列化违禁词表
	“””
    class Meta:
        model=Card
        fields = "__all__"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="2">
<li>views.py内编写逻辑视图</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from .models import UserProfile,Article,Comment,Card
from .serializers import UserProfileSerializer,ArticleSerializer,CommentSerializer,CardSerializer
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
# Create your views here.
class GetArticleView(APIView):
    """
    获取所有文章
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        article_list = Article.objects.all()
        re = ArticleSerializer(article_list, many=True)
        return Response(re.data)
class GetCommentView(APIView):
    """
    获取所有评论
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        Comment_list = Comment.objects.all()
        re = CommentSerializer(Comment_list, many=True)
        return Response(re.data)
#只是演示登录视图，并非实项目中可以使用的登录逻辑
class LoginView(APIView):
    """
    演示登录
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self, request):
        username=request._request.GET.get('username')
        if username:
            user=UserProfile.objects.filter(username=username).first()
            if user:
                re = UserProfileSerializer(user)
                return Response(re.data)
            else:
                return HttpResponse('404')
        else:
            return HttpResponse('404')
class PushArticleView(APIView):
    """
    发表文章类
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def post(self,request):
        title=request._request.POST.get('title')
        content=request._request.POST.get('content')
        user_id=request._request.POST.get('id')
        # print(title,content)
        if title and content and user_id:
            all_card=Card.objects.all()
            err=[]
            for i in all_card:
                j=title.find(i.word)
                if j!=-1:
                    err.append(i)
                k=content.find(i.word)
                if k!=-1:
                    err.append(i)
            if err:
                re = CardSerializer(err, many=True)
                return Response(re.data)
            article=Article()
            article.title=title
            article.content=content
            user=UserProfile.objects.filter(id=user_id).first()
            article.user=user
            article.save()
            return HttpResponse(200)
        else:
            return HttpResponse(404)
class PushCommentView(APIView):
    """
    发表评论
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def post(self, request):
        comment = request._request.POST.get('comment')
        user_id = request._request.POST.get('id')
        # print(comment,user_id)
        if comment and user_id:
            all_card = Card.objects.all()
            for i in all_card:
                comment=comment.replace(i.word,"***")
            newcomment=Comment()
            newcomment.content=comment
            user = UserProfile.objects.filter(id=user_id).first()
            newcomment.user=user
            #为了简化与本节知识点无关的内容，给评论的文章一个默认值
            article=Article.objects.filter(id=1).first()
            newcomment.article=article
            newcomment.save()
            return HttpResponse(200)
        else:
            return HttpResponse(404)
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>配置路由</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">from django.contrib import admin
from django.urls import path
#引入获取文章列表视图类，获取评论视图类
from app01.views import GetArticleView,GetCommentView
#引入获取登录视图类，获取发表文章视图类，发表评论视图类
from app01.views import LoginView,PushArticleView,PushCommentView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/',LoginView.as_view(),name='login'),
    path('getarticle/',GetArticleView.as_view(),name='getarticle'),
    path('getcomment/',GetCommentView.as_view(),name='getcomment'),
    path('pusharticle/',PushArticleView.as_view(),name='pusharticle'),
    path('pushcomment/',PushCommentView.as_view(),name='pushcomment')
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="4">
<li>解决跨域问题</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">pip install django-cors-headers<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">INSTALLED_APPS = [
#бнбн
    'rest_framework',
    'corsheaders'
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
	#引入跨域中间件，并放到首位
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<pre class="line-numbers language-none"><code class="language-none">CORS_ORIGIN_ALLOW_ALL = True<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="5">
<li>因为涉及post，关掉crf</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#注释掉验证csrf_token的中间件
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol start="9">
<li>demo7_3安装跨域模块</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">cnpm install axios -save<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<ol start="10">
<li>编写App.vue</li>
</ol>
<pre class="line-numbers language-none"><code class="language-none">&lt;template&gt;
  &lt;div id="app"&gt;
      &lt;div class="userinfo"&gt;
        用户名：{{username}}
      &lt;/div&gt;
      &lt;div class="login" v-if="flag"&gt;
        &lt;input type="text" v-model.lazy="username"&gt;
        &lt;button @click="Login()"&gt;登录&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="article" v-for="(item,index) in article" :key=index&gt;
        &lt;div class="title"&gt;{{item.title}}&lt;/div&gt;
        &lt;div class="content"&gt;{{item.content}}&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="commentlist" v-for="item in comment" :key=item.content&gt;
        &lt;div class="commentcontent"&gt;{{item.content}}&lt;/div&gt;
      &lt;/div&gt;
      &lt;div class="makecomment"&gt;
        评论内容:&lt;input type="text" v-model="pushcommet"&gt;
        &lt;button @click="PushComment()"&gt;提交评论&lt;/button&gt;
      &lt;/div&gt;
      &lt;div class="makearticle"&gt;
        &lt;div class="title"&gt;文章标题 &lt;input type="text" v-model="title"&gt; &lt;/div&gt;
        &lt;div class="content"&gt;文章内容 &lt;input type="text" v-model="content"&gt; &lt;/div&gt;
        &lt;button @click="PushArticle()"&gt;提交文章&lt;/button&gt;
      &lt;/div&gt;   
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import Axios from 'axios';
export default {
  name: 'app',
  data () {
    return {
      username: '',
      id:'',
      flag:true,
      article:[],
      title:'',
      content:'',
      comment:[],
      pushcommet:''
    }
  },
  methods:{
//登录方法
    Login(){
      var api='http://127.0.0.1:8000/login/?username='+this.username
       Axios.get(api)
      .then((response)=&gt;{
        // console.log(response.data.username);
        this.username=response.data.username
        this.id=response.data.id
        if(this.id){
          this.flag=false
        }       
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
},
//获取文章列表的方法
    GetArticle(){
      var api='http://127.0.0.1:8000/getarticle/'
      Axios.get(api)
      .then((response)=&gt;{
        console.log(response.data);
        this.article=response.data
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
},
//获取评论的方法
    GetComment(){
      var api='http://127.0.0.1:8000/getcomment/'
      Axios.get(api)
      .then((response)=&gt;{
        console.log(response.data);
        this.comment=response.data
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
},
//发表文章的方法
    PushArticle(){
      var api='http://127.0.0.1:8000/pusharticle/'
      var params = new URLSearchParams();
      params.append("title",this.title);
      params.append("content",this.content);
      params.append("id",this.id);
      console.log(params)
      Axios.post(api,params)
      .then((response)=&gt;{
        console.log(3333,response);
        if(response.data!=200){
          alert('存在违禁词')
        }
        this.GetArticle()
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
    },
//发表评论的方法
    PushComment(){
      var api='http://127.0.0.1:8000/pushcomment/'
      let data = {"title":this.title,"comment":this.pushcommet,"id":this.id};
      var params = new URLSearchParams();
      params.append("comment",this.pushcommet);
      params.append("id",this.id);
      console.log(params)
      Axios.post(api,params)
      .then((response)=&gt;{
        console.log(response);
        this.GetComment()
        })
      .catch((error)=&gt;{
        console.log(error)
        }
      )
    }
  },
  mounted(){
    this.GetArticle();
    this.GetComment()
  }
}
&lt;/script&gt;
&lt;style&gt;
*{
  box-sizing: border-box;
}
.userinfo{
  width: 300px;
  margin: 0 auto;
}
.login{
  width: 300px;
  margin: 0 auto;
}
.login input{
  width: 200px;
  margin: 0 auto;
}
.article{
  width: 300px;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 10px;
  border: 2px solid;
  padding: 5px;
}
.article .title{
  border-bottom: 1px solid;
}
.makecomment{
  width: 300px;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 10px;
}
.makecomment input{
  width: 150px;
}
.commentlist{
  width: 300px;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid;
  padding: 5px;
}
.makearticle{
  width: 300px;
  margin: 0 auto;
}
&lt;/style&gt;
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>









                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">lxx</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://xinxinliang.github.io/2021/02/24/python-django-web-dian-xing-mo-kuai-kai-fa-shi-zhan-shang/">http://xinxinliang.github.io/2021/02/24/python-django-web-dian-xing-mo-kuai-kai-fa-shi-zhan-shang/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">lxx</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%94%B5%E5%AD%90%E4%B9%A6/">
                                    <span class="chip bg-color">电子书</span>
                                </a>
                            
                                <a href="/tags/Django/">
                                    <span class="chip bg-color">Django</span>
                                </a>
                            
                                <a href="/tags/%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB/">
                                    <span class="chip bg-color">前后端分离</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220206.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="https://gitee.com/liangxinixn/guitar/raw/master/image01/20200726220308.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/02/24/python-django-web-dian-xing-mo-kuai-kai-fa-shi-zhan-xia/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-gj5e6q.jpg" class="responsive-img" alt="《Python Django Web典型模块开发实战》(下)">
                        
                        <span class="card-title">《Python Django Web典型模块开发实战》(下)</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-02-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%90%8E%E7%AB%AF%E6%A1%86%E6%9E%B6/" class="post-category">
                                    后端框架
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%94%B5%E5%AD%90%E4%B9%A6/">
                        <span class="chip bg-color">电子书</span>
                    </a>
                    
                    <a href="/tags/Django/">
                        <span class="chip bg-color">Django</span>
                    </a>
                    
                    <a href="/tags/%E5%89%8D%E5%90%8E%E7%AB%AF%E5%88%86%E7%A6%BB/">
                        <span class="chip bg-color">前后端分离</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/02/24/cong-ling-kai-shi-xue-python-wang-luo-pa-chong/">
                    <div class="card-image">
                        
                        <img src="https://cdn.jsdelivr.net/gh/liangxinxin5102/image2/cartoon01/wallhaven-g8p9j3.jpg" class="responsive-img" alt="《从零开始学Python网络爬虫》">
                        
                        <span class="card-title">《从零开始学Python网络爬虫》</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-02-24
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/python%E7%88%AC%E8%99%AB/" class="post-category">
                                    python爬虫
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%94%B5%E5%AD%90%E4%B9%A6/">
                        <span class="chip bg-color">电子书</span>
                    </a>
                    
                    <a href="/tags/%E6%BA%90%E7%A0%81%E7%89%88/">
                        <span class="chip bg-color">源码版</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 头号咸鱼<br />'
            + '文章作者: lxx<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021</span>
            
            <span id="year">2021</span>
            <a href="/about" target="_blank">lxx</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">272.8k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/xinxinliang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:1974733812@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1974733812" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1974733812" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    
    <script>
        (function (i, s, o, g, r, a, m) {
            i["DaoVoiceObject"] = r;
            i[r] = i[r] || function () {
                (i[r].q = i[r].q || []).push(arguments)
            }, i[r].l = 1 * new Date();
            a = s.createElement(o), m = s.getElementsByTagName(o)[0];
            a.async = 1;
            a.src = g;
            a.charset = "utf-8";
            m.parentNode.insertBefore(a, m)
        })(window, document, "script", ('https:' == document.location.protocol ? 'https:' : 'http:') +
            "//widget.daovoice.io/widget/6984b559.js", "daovoice")
        daovoice('init', {
            app_id: "7b318e23"
        });
        daovoice('update');
    </script>
    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
